package com.copa.l589;

import java.util.ArrayList;
import java.util.List;

/**
 * @author copa
 * @createDate 2022-08-30 10:12
 * @function 递归法
 */
public class Test1 {

    public List<Integer> preorder(Node root) {
        List<Integer> result = new ArrayList<>();
        // 由于在preorder()方法递归会导致result没有插入到值，所以再创一个方法为了能保证在list结果集存储
        result = addList(root, result);
        return result;
    }

    private List<Integer> addList(Node root, List<Integer> result) {
        if (root != null) {
            // 前序遍历，应该先把遍历到的节点加入到结果集再继续遍历
            result.add(root.val);
            if (root.children != null) {
                for (Node child : root.children) {
                    addList(child, result);
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        Node root = new Node(1);
        List<Node> child1 = new ArrayList<>();
        child1.add(new Node(3));
        child1.add(new Node(2));
        child1.add(new Node(4));
        root.children = child1;
        List<Node> child2 = new ArrayList<>();
        child2.add(new Node(5));
        child2.add(new Node(6));
        child1.get(0).children = child2;
        for (Integer result : new Test1().preorder(root)) {
            System.out.print(result + "\t");
        }

    }
}
